<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/6/8
 * Time: 21:59
 */

namespace Home\Logic;


use Home\Model\Page;

class MoneyLogLogic
{
    public function getMoneyLogList($user_id,$pagenum=1,$pagesize=10){
        $startno = ($pagenum - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $map['tp_money_log.user_id'] = ':user_id';
        $bind[':user_id'] = $user_id;

        $map['tp_money_log.type'] = ':type';
        $bind[':type'] = 1;
        $moneyLogList = D('MoneyLog')
            ->where($map)->bind($bind)->order('id desc')->limit($limit)
            ->select();
        foreach ($moneyLogList as $key=>$value){
            $moneyLogList[$key]['create_time'] = date("Y年m月d日", $moneyLogList[$key]['create_time']);
        }
        $data['list'] = $moneyLogList;
        $count = D('MoneyLog')->where($map)->bind($bind)->count();
        $page = new Page($pagenum, $count, $pagesize);
        $page = (array)$page;//转换为数组
        //分页数据
//        $page['cpage'] = $pagenum;//当前页面
//        $page['totalnum'] = floor(($count + $pagesize - 1) / $pagesize);
        $data['page'] = $page;

        return $data;
    }


    /**
     * @param $user_id 当前用户id
     * @param $score_id 来源用户id
     * @param $type 0代表充值 1代表返点,2表示购买商品 3提现 4退款
     * @param $put_type 0收入，1支出
     * @param $money  返点金额
     * @param $current_money 当前余额
     * @param $remark 备注
     */
    public function addMoneyLog($user_id, $score_id, $type, $put_type, $money, $current_money,$remark){
        $data = array(
            'user_id'  => $user_id,
            'source_id' => $score_id,
            'type'     => $type,
            'put_type' => $put_type,
            'money'    => $money,
            'current_money'  => $current_money,
            'remark'   => $remark,
            'create_time' => time()
        );
        M('MoneyLog')->add($data);
    }
    /**
     * 当代理购买商品是记录 用于返利使用以及平台查看记录
     * @param $user_id 当前用户id
     * @param $money  购买金额
     * @param $remark 备注
     */
    public function  addAgentLog($order_id, $remark = ''){

        $order = M('Order')->where(array('order_id'=> $order_id))->find();
        $user = M('Users')->where(array('user_id'=> $order['user_id']))->find();
        if($user['user_type'] != 1)
            return ;
        if($remark == '')
        {
            $remark = '代理商'.$user['nickname'].'购买商品';
        }
        $data = array(
            'user_id'  => $user['user_id'],
            'money'    => $order['goods_price'],
            'remark'   => $remark,
            'status'   => 0,
            'create_time'=> time()
        );
        M('AgentLog')->add($data);
        //调用存储过程更新self_month_sales, team_month_sales
        M()->query("call  updateSales({$user['user_id']}, {$order['goods_price']})");

    }
    /**
     * 若用户为普通用户而上级为代理商则将商品差价返给代理商
     * 同时把商品价格记录到用户销售额中
     * @param $order_id 订单ID
     */
    public function rebateAgentLog($order_id){
        $order = M('order')->where(array('order_id'=> $order_id))->find();
        $user = M('users')->where(array('user_id'=> $order['user_id']))->find();

        if($user['first_leader'])
            $leaderUser = M('users')->where(array('user_id'=> $user['first_leader']))->find();
        else
            return ;
        if($user['user_type'] == 0 && $leaderUser['user_type'] == 1){
            $sumRebateMoney = 0; //总的返利金额最后调用存储过程更新上级销售额时使用
            $agentMoney = 0;
            $callProPrice = 0;
            //找到所有购买商品ID
            $goodsIds = M('OrderGoods')->where(array('order_id'=> $order['order_id']))->field('goods_id,goods_num')->select();
            foreach ($goodsIds as $key => $val){
                 //拿代理差价agent_price
                $agentMoney = M('goods')->where(array('goods_id'=> $val['goods_id']))->getField('agent_price') * $val['goods_num'];
                $sumRebateMoney += $agentMoney;
                //记录到money_log表中
                $this->addMoneyLog($leaderUser['user_id'], $user['user_id'], 1, 0, $agentMoney, $leaderUser['user_money'], '下级普通用户购买商品返利差价');
                $leaderUser['user_money'] += $agentMoney;
            }
            //更新上级用户余额
            M('users')->save($leaderUser);
            $callProPrice = $order['goods_price']-$sumRebateMoney;
            //调用存储过程更新self_month_sales, team_month_sales
            M()->query("call  updateSales({$leaderUser['user_id']}, {$callProPrice})");
        }
    }


    //管理员每月返利时每位用户返利记录表
    /*        `user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
      `self_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时自身销售额',
      `team_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时下级自身销售额',
      `rebate_ratio` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时的返利比例',
      `rebate_money` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利金额',
      `create_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
      `remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',*/
    public function  addAgentRebateLog($user_id, $money, $self_month_sales, $team_month_sales, $rebate_ratio){
        $data = array(
            'user_id'      =>  $user_id,
            'self_month_sales' => $self_month_sales,
            'team_month_sales' => $team_month_sales,
            'rebate_ratio'     => $rebate_ratio,
            'rebate_money'     => $money,
            'create_time'      =>  time(),
            'remark'           => '代理商返利'
        );
        M('agent_rebate_log')->add($data);
    }



/*`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL DEFAULT '0' COMMENT '用户ID',
`self_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时自身销售额',
`one_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时下级自身销售额',
`two_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时下两级自身销售额',
`three_month_sales` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时下三级自身销售额',
`self_rebate_ratio` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时的自身返利比例',
`one_rebate_ratio` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时的下一级返利比例',
`two_rebate_ratio` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时的下两级返利比例',
`three_rebate_ratio` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利时的下三级返利比例',
`rebate_money` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '返利金额',
`create_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
`remark` varchar(255) NOT NULL DEFAULT '' COMMENT '备注',*/

    public function  newAddAgentRebateLog($user_id, $money, $self_month_sales, $one_month_sales,$two_month_sales, $three_month_sales, $self_rebate_ratio, $one_rebate_ratio, $two_rebate_ratio, $three_rebate_ratio){
        $data = array(
            'user_id'      =>  $user_id,
            'self_month_sales' => $self_month_sales,
            'one_month_sales' => $one_month_sales,
            'two_month_sales' => $two_month_sales,
            'three_month_sales' => $three_month_sales,
            'self_rebate_ratio'     => $self_rebate_ratio,
            'one_rebate_ratio'     => $one_rebate_ratio,
            'two_rebate_ratio'     => $two_rebate_ratio,
            'three_rebate_ratio'     => $three_rebate_ratio,
            'rebate_money'     => $money,
            'create_time'      =>  time(),
            'remark'           => '代理商返利'
        );
        M('agent_rebate_log')->add($data);
    }
}